//
//  CYCreditDetailVC.m
//  CreditAddressBook
//
//  Created by LE on 15/12/4.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYCreditDetailVC.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MBProgressHUD+MJ.h"
#import "CYABTool.h"
#import "CYDefaultDataTypeModl.h"
#import "CYDetailHeadView.h"
#import "CYDefatultHeaderCell.h"
#import "UITableViewCell+Category.h"
#import "CYDetailCell.h"
#import "CYTool.h"
#import "CYDefaultRecordAO.h"
#import "UIImageView+WebCache.h"
#import "CYCreditTool.h"
#import "CYCourtDetailCell.h"
#import "CYPromiseRecordModel.h"
#import "UITableView+SDAutoTableViewCellHeight.h"
#import "LEPhotoBrowserTool.h"
#import "LEBarButtonItem.h"
#import "CYDefaultRecordAO.h"


@interface CYCreditDetailVC ()<UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSNumber *cellH;
@property (nonatomic, strong) CYDefaultDataTypeModl *model;//多条违约记录
@property(nonatomic, weak) UITableViewCell *detailCell;
@property(nonatomic, strong) AFHTTPRequestOperation *httprequest;

@property(nonatomic, strong) CYDefaultRecordPics *defrs;//证据照片
@property(nonatomic,strong)UIView *bg;
@property (nonatomic , strong) UIView *shituview;


@end

@implementation CYCreditDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCancelBtn];
    [self setupTableView];
    [self loadDefrData];
    [CYTool setExtraCellLineHiddenWithTableView:self.tableView];
     
//     LEBarButtonItem *more = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"未标题-2-23"] andSelImage:nil andTitle:@"违约详情" target:self action:@selector(more)];
//     self.navigationItem.rightBarButtonItem = more;
     
}




-(void)more{
     CYDefaultDataTypeModl *model = self.model;
     NSArray *defaults = model.defaults;
     CYDefaultRecordAO *defrs = self.defr;
     defrs = defaults.firstObject;
     NSString *str = [NSString stringWithFormat:@"    %@于%@在**公司进行贷款，金额为:%@元,本该于%@之前进行还款，但至今仍未履行还款义务,逾期%@天,现对%@进行网络公示,望引起违约人的重视。\n    %@",defrs.name,    [CYCreditTool timewithLongLongValue:[defrs.lendTime longLongValue] formatter:nil],    defrs.amountPrice,     [CYCreditTool timewithLongLongValue:[defrs.startTime longLongValue] formatter:nil], [CYCreditTool dayWithStartValue:[NSNumber numberWithDouble:defrs.startTime.doubleValue] endValue:[NSNumber numberWithDouble:defrs.endTime.doubleValue]],defrs.name,defrs.memo];
     
     UIView *bgView = [[UIView alloc] initWithFrame:self.view.frame];
     bgView.backgroundColor = [UIColor grayColor];
     bgView.alpha = 0.8;
     self.bg = bgView;
     self.bg.hidden = NO;
     [[UIApplication sharedApplication].keyWindow addSubview:bgView];
     //     _shituview =[[UIView alloc]initWithFrame: CGRectMake(30,120,self.view.frame.size.width-60,400)];
     _shituview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.size.width/1.2, self.view.height/1.5)];
     _shituview.layer.cornerRadius = 5.0f;
     _shituview.center = self.view.center;
     _shituview.backgroundColor = [UIColor whiteColor];
     [[UIApplication sharedApplication].keyWindow addSubview:_shituview];
     [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_shituview];
     
     UIButton *quxiaoBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 20,20)];
     quxiaoBtn.layer.cornerRadius = 5.0f;
     [quxiaoBtn setImage:[UIImage imageNamed:@"icon_close_theme"] forState:UIControlStateNormal];
     [quxiaoBtn setTitle:@"取消" forState:UIControlStateNormal];
     [quxiaoBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
     [quxiaoBtn addTarget:self action:@selector(cancleclick) forControlEvents:UIControlEventTouchUpInside];
     [_shituview addSubview:quxiaoBtn];
     
     UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 30,_shituview.width , _shituview.height-35)];
     textView.editable = NO;
     textView.font = [UIFont systemFontOfSize:18.0f];
     textView.textColor = [UIColor grayColor];
     textView.text = str;
     [self.shituview addSubview:textView];
     
}
-(void)cancleclick{
     [_bg removeFromSuperview];
     [_shituview removeFromSuperview];
     
}

- (void)setupTableView {
    self.tableView = ({
        UITableView *table = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        [self.view addSubview:table];
        table.delegate = self;
        table.dataSource = self;
        table.separatorStyle = UITableViewCellSeparatorStyleNone;
        table.showsVerticalScrollIndicator = NO;
        table;
    });
}
/**
 *  通过ID从网络加载数据
 */
- (void)loadDefrData {
    [MBProgressHUD showMessage:nil toView:self.view];
    NSDictionary *params = @{@"id": self.defr.defaultRecordId, @"type": self.defr.type};
    __weak typeof(self) selfVC = self;
    self.httprequest = [CYABTool defaultRecordTypeModelsbyIdWithParams:params success:^(CYDefaultDataTypeModl *model) {
        [MBProgressHUD hideHUDForView:selfVC.view];
        //        self.defr = [defrs lastObject];
        selfVC.model = model;
        [selfVC.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:selfVC.view];
        CYLog(@"根据ID获取违约人详情错误：%@", error);
    }];
}
/**
 *  若pushTag为2或者3,表示该控制器是modal的
 */
- (void)setupCancelBtn {
    if (self.defr.pushTag != 1) {
        UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
        self.navigationItem.rightBarButtonItem = bar;
    }
}

- (void)cancelClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.model.defaults) {
        return self.model.defaults.count + 1;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CYDefaultDataTypeModl *model = self.model;
    NSArray *defaults = model.defaults;
    if (indexPath.section == 0) {
        CYDefaultRecordAO *defr = self.defr;
        if (!defr.name) {
            if (model.type == 0) {
                defr = defaults.firstObject;
            } else if (model.type == 1) {
                CYPromiseRecordModel *pr = defaults.firstObject;
                defr.name = pr.iname;
                defr.headPic = pr.headPic;
            }
        }
        CYDefatultHeaderCell *cell = [CYDefatultHeaderCell loadFromNibUsingClassName];
        if (defr.certificateNo) {
             
            cell.idCardLabel.text = CYStringFormat(@"身份证：%@", defr.certificateNo);
            NSDictionary *info = [CYCreditTool idCardInfo:defr.certificateNo];
            cell.ageLabel.text = CYStringFormat(@"年龄：%@", info[@"age"]);
            cell.sexLabel.text = CYStringFormat(@"性别：%@", info[@"sex"]);
        } else {
            cell.idCardLabel.text = CYStringFormat(@"身份证：%@", @"--");
            cell.ageLabel.text = CYStringFormat(@"年龄：%@", @"--");
            cell.sexLabel.text = CYStringFormat(@"性别：%@", @"--");
        }
          NSString *str = [NSString stringWithFormat:@"    %@于%@在**公司进行贷款，金额为:%@元,本该于%@之前进行还款，但至今仍未履行还款义务,逾期%@天,现对%@进行网络公示,望引起违约人的重视。",defr.name,    [CYCreditTool timewithLongLongValue:[defr.lendTime longLongValue] formatter:nil],    defr.amountPrice,     [CYCreditTool timewithLongLongValue:[defr.startTime longLongValue] formatter:nil], [CYCreditTool dayWithStartValue:[NSNumber numberWithDouble:defr.startTime.doubleValue] endValue:[NSNumber numberWithDouble:defr.endTime.doubleValue]],defr.name];
         if (str) {
              cell.detailTextView.text = str;
         }
         
         
        [cell.correctionBtn addTarget:self action:@selector(correctionBtn) forControlEvents:UIControlEventTouchUpInside];
        if (defr.headPic && !defr.headPic.isEmpty) {
            [cell.avatar sd_setImageWithURL:CYURLWithService(defr.headPic) placeholderImage:[UIImage imageNamed:@"icon_default_laolai"]];
        }
        cell.nameLabel.text = CYStringFormat(@"违约人：%@", defr.name);
        cell.iconIM.image = defr.iconImage;
         if (defr.phone && defr.phone.length>=10) {
              NSString *phonefont = [defr.phone substringToIndex:5];//截取掉下标5之后的字符串
              NSString *phonebehiend = [defr.phone substringFromIndex:7];//截取掉下标7之前的字符串
             cell.phoneLabel.text = [NSString stringWithFormat:@"电话号码:%@**%@", phonefont,phonebehiend];
              
         }else{
              cell.phoneLabel.text = @"电话号码:--";
         }
        return cell;
    } else {
        if (model.type == 0) {
            CYDefaultRecordAO *defr = defaults[indexPath.section - 1];
            CYDetailCell *cell = [CYDetailCell cellWithTableView:tableView];
            cell.defrs = @[defr];
            //            cell.frame = (CGRect){cell.frame.origin, CGSizeMake(cell.frame.size.width, 150 * defaults.count)};
            CYWeakObject(wself, self);
            [cell loadPhoto:tableView completion:^(CGFloat height) {
                [wself.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
            }];
             
            self.detailCell = cell;
            return cell;
        } else if (model.type == 1) {
            CYPromiseRecordModel *defr = defaults[indexPath.section - 1];
            CYCourtDetailCell *cell = [CYCourtDetailCell cellWithTableView:tableView];
            cell.model = defr;
            self.detailCell = cell;
            return cell;
        }
    }
    return nil;
}
/**
 *  号码纠错
 */
- (void)correctionBtn {
    
}

#pragma mark - delegate
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 500;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section != 0) {
        return [tableView fd_heightForCell:self.detailCell configuration:nil] ;
    }
    return 220;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section != 0) {
        return CYStringFormat(@"违约记录%ld", (long)section);
    }
    return @"";
}
/**
 *  设置的该方法，viewForHeaderInSection才会调用
 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section != 0) {
        return 12.0;
    }
    return .1;
}

#pragma mark - ARSegmentControllerDelegate

- (NSString *)segmentTitle {
    return @"违约详情";
}

- (UIScrollView *)streachScrollView {
    return self.tableView;
}

- (void)dealloc {
    CYLog(@"违约详情页销毁");
    [self.httprequest cancel];
}
@end
